package com.steamedfish.auctioncloudprocess.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.steamedfish.auctioncloudprocess.entiry.AuctionRegisterEntity;
import com.steamedfish.auctioncloudprocess.entiry.UserEntiry;
import com.steamedfish.auctioncloudprocess.feign.client.AuctionItemClient;
import com.steamedfish.auctioncloudprocess.mapper.AuctionRegisterMapper;
import com.steamedfish.auctioncloudprocess.model.AuctionItemModel;
import com.steamedfish.auctioncloudprocess.task.TaskScheduler;
import com.steamedfish.auctioncloudprocess.utils.DateTimeUtils;
import org.quartz.SchedulerException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 高山福
 * @since 2021-03-31
 */
@RestController
@RequestMapping("/auctioncloudprocess/auctionRegisterEntity")
public class AuctionRegisterController {


    @Autowired
    private AuctionRegisterMapper auctionRegisterMapper;

    @Autowired
    private AuctionItemClient auctionItemClient;

    @Autowired
    private TaskScheduler taskScheduler;


    @RequestMapping(value = "/registertoauction", method = RequestMethod.POST)
    public ResponseEntity<?> signUpForAuction(HttpServletRequest request,
                                              HttpServletResponse response,
                                              @RequestBody AuctionRegisterEntity data) throws ParseException, SchedulerException {


        //数据校验：商品id，用户id，保证金，创建日期，逻辑删除
        //获取用户信息
        String userToken = null;
        UserEntiry userEntiry = null;
        String userId = null;
        try {
            userToken = SecurityContextHolder.getContext().getAuthentication().getName();
            userEntiry = JSON.parseObject(userToken, UserEntiry.class);
            userId = userEntiry.getId();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok("failed");
        }


        //获取商品id
        if (data.getItemId() == null) {
            return ResponseEntity.ok("failed");
        }

        //创建报名表信息
        String id = "auction_process_" + UUID.randomUUID();
        String deposit = "2";
        LocalDateTime createTime = LocalDateTime.now();
        String deleted = "0";

        //封装报名表信息
        AuctionRegisterEntity auctionRegisterEntity = new AuctionRegisterEntity();
        auctionRegisterEntity.setItemId(data.getItemId());
        auctionRegisterEntity.setUserId(userId);
        auctionRegisterEntity.setDeposit(deposit);
        auctionRegisterEntity.setCreateTime(createTime);
        auctionRegisterEntity.setDeleted(deleted);
        auctionRegisterEntity.setId(id);


        System.out.println(JSON.toJSON(auctionRegisterEntity));

        //插入数据
        auctionRegisterMapper.insert(auctionRegisterEntity);

        //开启定时任务（用于提醒）
        try {
            taskScheduler.triggerStartAuctionAlertTask(auctionRegisterEntity.getItemId(), getAuctionTime(auctionRegisterEntity.getItemId()));
        } catch (Exception e) {

        }

//        taskScheduler.triggerAuctionResultAdTask(auctionRegisterEntity.getItemId(), getEndTime(auctionRegisterEntity.getItemId()));

        return ResponseEntity.ok("success");
    }


    @RequestMapping(value = "/status", method = RequestMethod.POST)
    public ResponseEntity<?> registerStatus(HttpServletRequest request,
                                            HttpServletResponse response,
                                            @RequestBody AuctionRegisterEntity data){

        //获取用户信息
        //获取用户信息
        String userToken = null;
        UserEntiry userEntiry = null;
        String userId = null;
        try {
            userToken = SecurityContextHolder.getContext().getAuthentication().getName();
            userEntiry = JSON.parseObject(userToken, UserEntiry.class);
            userId = userEntiry.getId();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok("failed");
        }

        //校验拍品id
        if (data.getItemId() == null) {
            return ResponseEntity.ok("failed");
        }
        String itemId = data.getItemId();


        //查询商品信息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("item_id", itemId);
        queryWrapper.eq("user_id", userId);
        AuctionRegisterEntity auctionRegisterEntity = auctionRegisterMapper.selectOne(queryWrapper);
        if (auctionRegisterEntity == null) {
            return ResponseEntity.ok("0");  //未报名
        } else if (auctionRegisterEntity != null && (auctionRegisterEntity.getDeposit() == null || auctionRegisterEntity.getDeposit().equals(""))) {
            return ResponseEntity.ok("1");  //未支付
        } else if (auctionRegisterEntity.getDeposit() != null && !auctionRegisterEntity.getDeposit().equals("")) {
            return ResponseEntity.ok("2");  //已报名并完成支付
        } else {
            return ResponseEntity.ok("failed");
        }
    }


    @RequestMapping(value = "/subscription", method = RequestMethod.POST)
    public ResponseEntity<?> getSub(HttpServletRequest request,
                                            HttpServletResponse response,
                                            @RequestBody AuctionRegisterEntity data){

        //获取用户信息
        //获取用户信息
        String userToken = null;
        UserEntiry userEntiry = null;
        String userId = null;
        try {
            userToken = SecurityContextHolder.getContext().getAuthentication().getName();
            userEntiry = JSON.parseObject(userToken, UserEntiry.class);
            userId = userEntiry.getId();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok("failed");
        }


        //查询商品信息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        List<AuctionRegisterEntity> auctionRegisterEntitys = auctionRegisterMapper.selectList(queryWrapper);

        List<AuctionItemModel> auctionItemModelList = new ArrayList<>();
        for (int i = 0; i < auctionRegisterEntitys.size(); i++) {
            AuctionItemModel auctionItemModel = auctionItemClient.getAuctionItemModel(auctionRegisterEntitys.get(i).getItemId());
            auctionItemModelList.add(auctionItemModel);
        }
        auctionItemModelList.sort(Comparator.comparing(AuctionItemModel::getCreateTime).reversed());
        System.out.println(auctionItemModelList);
        return ResponseEntity.ok(auctionItemModelList);
    }


    /**
     * 获取指定id商品的开始拍卖时间
     *
     * @param id
     * @return int
     */
    public Date getAuctionTime(String id) throws ParseException {
        AuctionItemModel auctionItemModel = auctionItemClient.getAuctionItemModel(id);
        String time = auctionItemModel.getAuctionTime();
        Date date = DateTimeUtils.StringToDate(time);
        Date preDate = DateTimeUtils.preTime(date, 300000);
        return preDate;
    }

    /**
     * 获取拍品结束的时间
     *
     * @param id
     * @return int
     */
    public Date getEndTime(String id) throws ParseException {
        AuctionItemModel auctionItemModel = auctionItemClient.getAuctionItemModel(id);
        String time = auctionItemModel.getEndTime();
        Date date = DateTimeUtils.StringToDate(time);
        Date afterDate = DateTimeUtils.afterTime(date, 30000);
        return afterDate;
    }


}
